#!/bin/bash

#default variables
program_name="a.out"
time_limit=1
comparer="diff -wb"
each_point=10
report_filename="report.log"
TIMEFORMAT="%Es"
#end

while [ "$1" != "" ]
do case "$1" in
    --time-limit=* )
        time_limit=${1#--time-limit=}
    ;;
    --input-format=* )
        input_format=${1#--input-format=}
    ;;
    --output-format=* )
        output_format=${1#--output-format=}
    ;;
    --input-filename=* )
        input_filename=${1#--input-filename=}
    ;;
    --output-filename=* )
        output_filename=${1#--output-filename=}
    ;;
    --comparer=* )
        comparer=${1#--comparer=}
    ;;
    --each-point=* )
        each_point=${1#--each-point=}
    ;;
    --report-filename=* )
        report_filename=${1#--report-filename=}
    ;;
    --time-format=* )
        TIMEFORMAT=${1#--time-format=}
    ;;
    * ) program_name=$1 ;;
esac
shift
done

#default format variables
if [ "$input_format" == "" ]
then input_format="$program_name"'@.in'
fi
if [ "$output_format" == "" ]
then output_format="$program_name"'@.out'
fi
if [ "$input_filename" == "" ]
then input_filename="$program_name.in"
fi
if [ "$output_filename" == "" ]
then output_filename="$program_name.out"
fi
#end

#check if file exists
if [ ! -x "$program_name" ]
then echo 'Program "'"$program_name"'" not found or not marked as executable.'
exit
fi
#end

FOR=`echo $input_format | tr '@' '*'`
in_pre=${input_format%@*}
in_suff=${input_format#*@}
out_pre=${output_format%@*}
out_suff=${output_format#*@}
full_point=0
your_point=0
rm -f $report_filename
printf "%s\t%s\t\t\t%s\n" 'Case' 'Status' 'Time' | tee -a "$report_filename"
for i in $FOR
do
    if [ $i == $input_filename ] 
    then continue;
    fi
    tmp=${i%$in_suff}
    mid=${tmp#$in_pre}
    full_point=$( expr $each_point + $full_point );
    cp "$i" "$input_filename"
    exec_stderr=`(time timeout "$time_limit" "./$program_name") 2>&1`
    ret_value=$?
    result=""
    color=0
    if [ $ret_value -eq 0 ]
    then
        $comparer "$output_filename" "$out_pre""$mid""$out_suff" > /dev/null
        if [ $? -eq 0 ]
        then 
            result='Correct            '
            color=34
            your_point=$( expr $each_point + $your_point )
        else
            result='Wrong Answer       '
            color=31
        fi
    else
        if [ $ret_value -eq 124 ]
        then
            result='Time Limit Exceeded';
            color=36
        else
            result='Runtime Error      '
            color=33
        fi
    fi
    printf "%s\t\33[%dm%s\33[0m\t%s\t\n" "$mid" "$color" "$result" "$exec_stderr" | tee -a "$report_filename"
done

printf "full points : %d\nyour points : \33[5m%d\33[0m\n" $full_point $your_point
